package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdChannelMapper;
import com.heima.admin.service.AdChannelService;
import com.heima.model.admin.dtos.ChannelDto;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Transactional
public class AdChannelServiceImpl extends ServiceImpl<AdChannelMapper, AdChannel> implements AdChannelService {
    @Override
    public ResponseResult findByPageAndName(ChannelDto dto) {
        if (dto==null){
           return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Page<AdChannel> page =new Page(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<AdChannel> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(dto.getName())){
            queryWrapper.like(AdChannel::getName,dto.getName());
        }
        IPage<AdChannel> channelIPage = this.page(page, queryWrapper);
            ResponseResult responseResult =new PageResponseResult(dto.getPage(),dto.getSize(),channelIPage.getTotal());
            responseResult.setData(channelIPage.getRecords());
        return responseResult;
    }

    @Override
    public ResponseResult insert(AdChannel channel) {
        if (channel==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        channel.setIsDefault(false);
        channel.setCreatedTime(new Date());
        this.save(channel);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult update(AdChannel adChannel) {
        if (adChannel==null||adChannel.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        this.updateById(adChannel);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult deleteById(Integer id) {
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        this.removeById(id);
        return ResponseResult.okResult();
    }
}
